<?php

namespace Fox;

class ErrorHandle {


	private $mode;
	private $url;
	function __construct($pars) {
		$this->mode = $pars['mode'];
		$this->url = $pars['url'];
	}

	function register() {
		set_exception_handler([$this, 'errorHandler']);
		set_error_handler([$this, 'errorHandler']);
		register_shutdown_function([$this, 'errorShutdown']);
	}

	function errorShutdown() {
		$error = error_get_last();
		if ($error && ($error['type'] != E_NOTICE || $error['type'] != E_STRICT)) {
			$this->show($error['message'], array($error), null);
		}
	}

	function errorHandler($errno_exp, $errstr = '', $errfile = '', $errline = '') {
		if ($errno_exp == E_NOTICE || $errno_exp == E_STRICT) {
			return;
		}
		if (is_numeric($errno_exp)) {
			$msg = $errstr;
			$traces = debug_backtrace();
		} else {
			$msg = $errno_exp->getMessage();
			$traces = $errno_exp->getTrace();
			$first['file'] = $errno_exp->getFile();
			$first['line'] = $errno_exp->getLine();
			$first['class'] = '';
			$first['function'] = '';
			array_unshift($traces, $first);
		}
		$this->show($msg, $traces, $errno_exp);
	}

	function show($msg, $traces, $errno_exp) {

		if($this->mode == 'url'){
			header("Location: $this->url");
			die();
		}

		echo "<!DOCTYPE html><html><head><style>
			h1{color:#f00;} ul{list-style: none;} p,pre{text-indent:0em; background-color:#FFFFCC;padding:1em;} td{border:1px solid #ccc; padding:0.5em;    background-color: #FFFFCC } table{   border-collapse: collapse;}</style></head><body><h1>Error</h1><p>";
		echo $msg;
		echo "</p>";
		if ($errno_exp instanceof \PDOException && $GLOBALS['_last_db_']) {
			$GLOBALS['_last_db_']->printError();
		}
		echo "<h1>Traces</h1><table><tr><td>NO.</td><td>File</td> <td>Line</td><td>Class</td><td>Function</td></tr>";
		for ($i = 0; $i < count($traces); $i++) {
			$value = $traces[$i];
			$index = $i + 1;
			if (!empty($value) && isset($value['file'])) {
				$file = str_replace($_SERVER['DOCUMENT_ROOT'], '', $value['file']);
				echo "<tr><td>$index</td><td>$file</td><td>$value[line]</td><td>" . (isset($value['class']) ? $value['class'] : '') . "</td><td>" . (isset($value['function']) ? $value['function'] : '') . "</td></tr>";
			}
		}
		echo "</table></body></html>";
		die();
	}

}
